const express = require('express');
const router = express.Router();
const { Course, Category, Chapter, User } = require('../../models');
const { success, failure } = require('../../utils/responses');
const { NotFound, Forbidden } = require('http-errors');

/**
 * 检查用户是否能浏览当前章节
 * @param req
 * @param chapter
 * @returns {Promise<void>}
 */
const checkUserRole = async (req, chapter) => {
  // 如果章节是免费的
  if (chapter.free) {
    return;
  }

  // 检查用户是否有权限访收费章节
  const allowedRoles = [1, 100]; // 大会员和管理员的角色ID
  const user = await User.findByPk(req.user.id);
  if (!allowedRoles.includes(user.role)) {
    throw new Forbidden('您没有权限浏览，请先购买大会员后再访问。');
  }
};

/**
 * 查询章节列表
 * GET /web/chapters
 */
router.get('/', async function (req, res) {
  try {
    const { courseId } = req.query;

    const course = await Course.findByPk(courseId);
    if (!course) {
      throw new NotFound(`ID: ${courseId}的课程未找到。`);
    }
    // 同属一个课程的所有章节
    const chapters = await Chapter.findAll({
      attributes: { exclude: ['CourseId', 'content'] },
      where: { courseId: courseId },
      order: [
        ['rank', 'ASC'],
        ['id', 'DESC'],
      ],
    });
    success(res, '查询章节成功。', { data: chapters });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询章节详情
 * GET /web/chapters/:id
 */
router.get('/:id', async function (req, res) {
  try {
    const { id } = req.params;

    const chapter = await Chapter.findByPk(id, {
      attributes: { exclude: ['CourseId'] },
    });
    if (!chapter) {
      throw new NotFound(`ID: ${id}的章节未找到。`);
    }

    // 检查用户是否能浏览当前章节
    await checkUserRole(req, chapter);

    // 查询章节关联的课程
    const course = await chapter.getCourse({
      attributes: ['id', 'name', 'userId'],
    });
    const [user, chapters] = await Promise.all([
      // 查询课程关联的用户
      course.getUser({
        attributes: ['id', 'username', 'nickname', 'avatar', 'company'],
      }),
      // 同属一个课程的所有章节
      Chapter.findAll({
        attributes: { exclude: ['CourseId', 'content'] },
        where: { courseId: chapter.courseId },
        order: [
          ['rank', 'ASC'],
          ['id', 'DESC'],
        ],
      }),
    ]);

    success(res, '查询章节成功。', { chapter, course, user, chapters });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
